import wepy from 'wepy'
import api from '@/api'

export function getCurrentTime() {
  var keep = '';
  var date = new Date();
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? '0' + m : m;
  var d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
  var h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
  var f = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
  var s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
  var rand = Math.round(Math.random() * 899 + 100);
  keep = y + '' + m + '' + d + '' + h + '' + f + '' + s;
  return keep; //20160614134947
}
// 时间格式化输出，如11:03 25:19 每1s都会调用一次
export function dateformat(micro_second) {
  // 总秒数
  var second = Math.floor(micro_second / 1000);
  // 天数
  var day = Math.floor(second/3600/24);
  // 小时
  var hr = Math.floor(second/3600%24);
  // 分钟
  var min = Math.floor(second/60%60);
  // 秒
  var sec = Math.floor(second%60);
  return (day ? (day + '天') : '') + (hr ? (hr + '小时') : '') + (min ? (min + '分钟') : '') + (sec ? (sec + '秒') : '')
 }
// 时间格式化
export function formatDate (date, type) {
  if (!date) return ''
  if (typeof date === 'string') {
    date = date.replace(/-/g, '/')
  }
  date = (typeof date === 'number' || typeof date === 'string') ? new Date(date) : date
  type = type || 'yyyy-MM-dd HH:mm:ss'
  let obj = {
    'y': date.getFullYear(), // 年份，注意必须用getFullYear
    'M': date.getMonth() + 1, // 月份，注意是从0-11
    'd': date.getDate(), // 日期
    'q': Math.floor((date.getMonth() + 3) / 3), // 季度
    'w': date.getDay(), // 星期，注意是0-6
    'H': date.getHours(), // 24小时制
    'h': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 12小时制
    'm': date.getMinutes(), // 分钟
    's': date.getSeconds(), // 秒
    'S': date.getMilliseconds() // 毫秒
  }
  let week = ['天', '一', '二', '三', '四', '五', '六']
  for (let i in obj) {
    type = type.replace(new RegExp(i + '+', 'g'), function (m) {
      let val = obj[i] + ''
      if (i === 'w') return (m.length > 2 ? '星期' : '周') + week[val]
      for (let j = 0, len = val.length; j < m.length - len; j++) val = '0' + val
      return m.length === 1 ? val : val.substring(val.length - m.length)
    })
  }
  return type
}

//验证是否是手机号码
export function vailPhone(number) {
  let flag = false;
  let myreg = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/;
  if (number.length != 11) {
    flag = flag;
  }else if (!myreg.test(number)) {
    flag = flag;
  }else{
    flag = true;
  }
  return flag;
}

//浮点型除法
export function div(a, b) {
  var c, d, e = 0,
    f = 0;
  try {
    e = a.toString().split(".")[1].length;
  } catch (g) { }
  try {
    f = b.toString().split(".")[1].length;
  } catch (g) { }
  return c = Number(a.toString().replace(".", "")), d = Number(b.toString().replace(".", "")), mul(c / d, Math.pow(10, f - e));
}
//浮点型加法函数   
export function accAdd(arg1, arg2) {
  var r1, r2, m;
  try {
    r1 = arg1.toString().split(".")[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split(".")[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2));
  return ((arg1 * m + arg2 * m) / m).toFixed(2);
}
//浮点型乘法
export function mul(a, b) {
  var c = 0,
    d = a.toString(),
    e = b.toString();
  try {
    c += d.split(".")[1].length;
  } catch (f) { }
  try {
    c += e.split(".")[1].length;
  } catch (f) { }
  return Number(d.replace(".", "")) * Number(e.replace(".", "")) / Math.pow(10, c);
}

// 遍历对象属性和值
export function displayProp(obj) {
  var names = "";
  for (var name in obj) {
    names += name + obj[name];
  }
  return names;
}
// 去除字符串所有空格
export function sTrim(text) {
  return text.replace(/\s/ig, '')
}
//去除所有:
export function replaceMaohao(txt) {
  return txt.replace(/\:/ig, '')
}
//转换星星分数
export function convertStarArray(score) {
  //1 全星,0 空星,2半星 
  var arr = []
  for (var i = 1; i <= 5; i++) {
    if (score >= i) {
      arr.push(1)
    } else if (score > i-1 && score < i + 1) {
      arr.push(2)
    } else {
      arr.push(0)
    }
  }
  return arr
}
// 合并数组
export function mergeArray (arr1, arr2) {
  if (arr1 instanceof Array && arr2 instanceof Array) {
    arr2.map(item => {
      arr1.push(item)
    })
  }
  return arr1
}
// 数组内时间批量处理
export function formatDateArray (array, key, type = 'yyyy/MM/dd HH:mm') {
  if (array instanceof Array) {
    array.forEach(item => {
      item[key] = formatDate(item[key], type)
    })
  }
  return array
}
/*
 获取domain
 url:需要排序的字段
 */
export function getDomain (url) {
  if (url.indexOf('www') > -1) {
    url = url.slice((url.indexOf('.') + 1))
  } else if (url.indexOf('yu') > -1) {
    url = url.replace('yu.', '')
  }
  return url
}

/*
 订单状态
 */
export function getOrderStatus (str) {
  let status = ''
  switch (str) {
    case 1:
      status = '待支付'
      break
    case 2:
      status = '已支付'
      break
    case 3:
      status = '支付失败'
      break
    case 4:
      status = '已完成'
      break
    case 5:
      status = '已关闭'
      break
    case 6:
      status = '退款中'
      break
    case 7:
      status = '已退货'
      break
    case 9:
      status = '预下单成功'
      break
    case 10:
      status = '已取消'
      break
    default:
      break
  }
  return status
}

/*
 表单校验
 */
export function validator (form, rules) {
  let validator = {}
  for (let key in form) {
    if (rules[key]) {
      for (let item in rules[key]) {
        if (rules[key][item].required && (!form[key] || form[key] === '')) {
          validator.message = rules[key][item].message
          validator.name = key
          break
        } else if (rules[key][item].min && rules[key][item].min > form[key].length) {
          validator.message = rules[key][item].message
          validator.name = key
          break
        } else if (rules[key][item].max && rules[key][item].max < form[key].length) {
          validator.message = rules[key][item].message
          validator.name = key
          break
        } else if (rules[key][item].pattern && !rules[key][item].pattern.test(form[key])) {
          validator.message = rules[key][item].message
          validator.name = key
          break
        }
      }
      if (validator.message) {
        break
      }
    }
  }
  return validator
}

/*
产品详情json字符串处理
*/
export function jsonTidy (str) {
  let json = {}
  str = JSON.parse(str)
  str.forEach(item => {
    json[item.name] = item
  })
  return json
}

export function formatPrice (value) {
  value = Math.round(parseFloat(value)*100)/10000
  var xsd = value.toString().split(".")
  if (xsd.length == 1) {
    value = value.toString() + ".00"
    return value
  }
  if (xsd.length > 1) {
    if (xsd[1].length < 2) {
      value = value.toString() + "0"
    }
    return value
  }
}

export function timeScope (start, end) {
  let str = ''
  if (start === end || !end) {
    str = formatDate(start, 'yyyy/MM/dd ww HH:mm')
  } else {
    str = formatDate(start, 'yyyy/MM/dd ww') + ' ~ ' + formatDate(end, 'yyyy/MM/dd ww')
  }
  return str
}
